import request from '@/utils/request'

// ==================== 接口类型定义 ====================

/**
 * 支付信息接口
 */
export interface PaymentInfo {
  payment_id: number
  order: number
  order_no: string
  payment_type: number
  transaction_id: string | null
  payment_amount: string
  payment_status: number
  payment_time: string | null
  callback_content: string | null
  callback_time: string | null
  create_time: string
  update_time: string
}

/**
 * 支付请求参数接口
 */
export interface PayOrderParams {
  payment_type?: number
}

/**
 * 支付响应接口
 */
export interface PayOrderResponse {
  message: string
  payment_id: number
  transaction_id: string
}

/**
 * 支付方式枚举
 */
export enum PaymentType {
  Alipay = 1,
  Wechat = 2,
}

/**
 * 支付状态枚举
 */
export enum PaymentStatus {
  Unpaid = 0,
  Paid = 1,
}

// ==================== API 服务 ====================

/**
 * 支付API服务
 */
export const paymentApi = {
  /**
   * 获取支付信息
   * GET /payment/orders/{order_id}/payment/
   * @param order_id - 订单ID
   */
  getPaymentInfo(order_id: number): Promise<PaymentInfo> {
    return request({
      url: `/payment/orders/${order_id}/payment/`,
      method: 'get',
    })
  },

  /**
   * 处理支付请求
   * POST /payment/orders/{order_id}/pay/
   * @param order_id - 订单ID
   * @param params - 支付参数
   */
  payOrder(order_id: number, params: PayOrderParams = {}): Promise<PayOrderResponse> {
    return request({
      url: `/payment/orders/${order_id}/pay/`,
      method: 'post',
      data: params,
    })
  },
}

// ==================== 工具函数 ====================

/**
 * 格式化金额
 */
export const formatAmount = (amount: number): string => {
  return amount.toFixed(2)
}

/**
 * 获取支付方式名称
 */
export const getPaymentTypeName = (paymentType: PaymentType): string => {
  const typeNames: Record<PaymentType, string> = {
    [PaymentType.Alipay]: '支付宝',
    [PaymentType.Wechat]: '微信',
  }
  return typeNames[paymentType] || '未知支付方式'
}

/**
 * 获取支付状态名称
 */
export const getPaymentStatusName = (paymentStatus: PaymentStatus): string => {
  const statusNames: Record<PaymentStatus, string> = {
    [PaymentStatus.Unpaid]: '未支付',
    [PaymentStatus.Paid]: '已支付',
  }
  return statusNames[paymentStatus] || '未知状态'
}

// ==================== 默认导出 ====================

export default paymentApi
